using System;
using System.Resources;
using System.Drawing;
using System.Collections;
using System.Reflection;
using System.ComponentModel;
using System.Text;
using System.IO;
using Microsoft.BizTalk.Message.Interop;
using Microsoft.BizTalk.Component.Interop;
using System.Xml;
using Microsoft.Samples.BizTalk.Pipelines.CustomComponent;

namespace HIPAA_Pipelines
{

    [ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
    [ComponentCategory(CategoryTypes.CATID_Any)]
    [ComponentCategory(CategoryTypes.CATID_Validate)]
    [System.Runtime.InteropServices.Guid("9d0e4103-4cce-4536-83fa-4a5040674ad6")]
    public class Availity_HTTP_Response_EDIParser_Component :
        IBaseComponent,
        Microsoft.BizTalk.Component.Interop.IComponent,
        Microsoft.BizTalk.Component.Interop.IPersistPropertyBag,
        IComponentUI
    {
        static ResourceManager resManager = new ResourceManager("Availity_HTTP_Response_EDIParser_Component", Assembly.GetExecutingAssembly());


        // Component information
        #region IBaseComponent
        public string Name { get { return "Availity HTTP Response EDI Parser Component"; } }
        public string Version { get { return "1.0"; } }
        public string Description { get { return "Parses an Availity HTTP Response and extracts the EDI string for the EDI Dissasembler."; } }
        public IntPtr Icon
        {
            get
            {
                return new System.IntPtr();
            }
        }
        public System.Collections.IEnumerator Validate(object projectSystem)
        {
            return null;
        }

        #endregion

        private string _XPATH_to_EDI;
        [
        DisplayName("XPATH Statement to the EDI Body"),
        Description(@"Example: /*[local-name()='Envelope' and namespace-uri()='http://HealthcareClaimSchemas.Availity.Availity_HTTP_Request']/*[local-name()='Body' and namespace-uri()='']
                        or /*[local-name()='ENVELOPE' and namespace-uri()='http://HealthcareClaimSchemas.Availity.Availity_HTTP_X12_Response']/*[local-name()='BODY' and namespace-uri()='']")
        ]
        public string XPATH_to_EDI_Section
        {
            get { return _XPATH_to_EDI; }
            set { _XPATH_to_EDI = value; }
        }
        


        #region IPersistPropertyBag Members

        public void InitNew()
        {
        }

        public void GetClassID(out Guid classID)
        {
            classID = new Guid("48BEC85A-20EE-40ad-BFD0-319B59A0DDBC");
        }

        public void Load(IPropertyBag propertyBag, int errorLog)
        {
            string val = (string)ReadPropertyBag(propertyBag, "XPATH_to_EDI_Section");
            if (val != null) XPATH_to_EDI_Section = val;

            

        }
        public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
        {
            object val = (object)XPATH_to_EDI_Section;
            WritePropertyBag(propertyBag, "XPATH_to_EDI_Section", val);

        }

        #endregion

        #region IComponent Members
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {

            //We need to pull out the EDI Text and send it as the Body

            //Try and read in the message to determine the type
                IBaseMessagePart bodyPart = pInMsg.BodyPart;
                if (bodyPart != null)
                {
                    Stream originalStream = bodyPart.GetOriginalDataStream();
                    if (originalStream != null)
                    {
                        //Load up the inbound unenriched EDI Document
                        XmlDocument _originalDocument = new XmlDocument();
                        _originalDocument.Load(originalStream);

                        //Pull out the EDI
                        string EDIData = _originalDocument.SelectSingleNode(XPATH_to_EDI_Section).InnerText;

                        MemoryStream _stream = new MemoryStream(Encoding.ASCII.GetBytes(EDIData));

                        //Set the position to the beginning
                        _stream.Position = 0;

                        pInMsg.BodyPart.Data = _stream;

                        pContext.ResourceTracker.AddResource(pInMsg.BodyPart.Data);
                    }
                }
                return pInMsg;                       
            
        }
            
        
        #endregion
        #region Helper Methods

        /// <summary>
        /// Reads property value from property bag.
        /// </summary>
        /// <param name="pb">Property bag.</param>
        /// <param name="propName">Name of property.</param>
        /// <returns>Value of the property.</returns>
        private static object ReadPropertyBag(Microsoft.BizTalk.Component.Interop.IPropertyBag pb, string propName)
        {
            object val = null;
            try
            {
                pb.Read(propName, out val, 0);
            }

            catch (ArgumentException)
            {
                return val;
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
            return val;
        }

        /// <summary>
        /// Writes property values into a property bag.
        /// </summary>
        /// <param name="pb">Property bag.</param>
        /// <param name="propName">Name of property.</param>
        /// <param name="val">Value of property.</param>
        private static void WritePropertyBag(Microsoft.BizTalk.Component.Interop.IPropertyBag pb, string propName, object val)
        {
            try
            {
                pb.Write(propName, ref val);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }
        #endregion
    }
}

